"""
应用配置管理
"""

from pydantic_settings import BaseSettings
from typing import List, Optional


class Settings(BaseSettings):
    """应用配置类 - 所有配置项都从.env文件加载"""
    
    # 应用基础配置
    APP_NAME: str
    APP_VERSION: str
    DEBUG: bool
    API_V1_STR: str
    
    # 服务器配置
    BACKEND_HOST: str
    BACKEND_PORT: int
    
    # 数据库配置
    MONGODB_URL: str
    MONGODB_DATABASE: str
    MONGODB_USER: Optional[str] = None
    MONGODB_PASSWORD: Optional[str] = None
    
    # Redis配置
    REDIS_URL: str
    REDIS_PASSWORD: Optional[str] = None
    CACHE_TTL: int
    CACHE_PREFIX: str
    
    # MinIO配置
    MINIO_ENDPOINT: str
    MINIO_ACCESS_KEY: str
    MINIO_SECRET_KEY: str
    MINIO_BUCKET_NAME: str
    MINIO_SECURE: bool
    
    # JWT配置
    JWT_SECRET_KEY: str
    JWT_ALGORITHM: str
    JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int
    JWT_REFRESH_TOKEN_EXPIRE_DAYS: int
    
    # CORS配置
    ALLOWED_ORIGINS: List[str] = []
    # 可信主机（生产应配置具体域名/IP）
    ALLOWED_HOSTS: List[str] = ["*"]

    # 文档预览/编辑服务配置
    DOCUMENT_PREVIEW_ENABLED: bool = False
    DOCUMENT_PREVIEW_PROVIDER: str = "legacy"
    DOCUMENT_PREVIEW_SERVICE_URL: Optional[str] = None
    DOCUMENT_PREVIEW_CALLBACK_URL: Optional[str] = None
    DOCUMENT_PREVIEW_PUBLIC_URL: Optional[str] = None
    DOCUMENT_PREVIEW_AUTH_SECRET: Optional[str] = None

    DOCUMENT_EDITOR_ENABLED: bool = False
    DOCUMENT_EDITOR_PROVIDER: str = "legacy"
    DOCUMENT_EDITOR_SERVICE_URL: Optional[str] = None
    DOCUMENT_EDITOR_CALLBACK_URL: Optional[str] = None
    DOCUMENT_EDITOR_PUBLIC_URL: Optional[str] = None
    DOCUMENT_EDITOR_AUTH_SECRET: Optional[str] = None
    
    @property
    def allowed_origins(self) -> List[str]:
        """获取允许的源列表，开发环境下自动添加常见前端地址"""
        origins = list(self.ALLOWED_ORIGINS) if self.ALLOWED_ORIGINS else []
        
        # 开发环境下，自动添加常见的前端开发地址
        if self.DEBUG:
            default_origins = [
                "http://localhost:3000",
                "http://localhost:5173",  # Vite 默认端口
                "http://localhost:5174",
                "http://localhost:8080",
                "http://localhost:8081",
                "http://127.0.0.1:3000",
                "http://127.0.0.1:5173",
                "http://127.0.0.1:5174",
                "http://127.0.0.1:8080",
                "http://127.0.0.1:8081",
            ]
            # 去重并合并
            for origin in default_origins:
                if origin not in origins:
                    origins.append(origin)
        
        return origins if origins else ["*"]
    
    # 安全配置
    BCRYPT_ROUNDS: int
    SESSION_TIMEOUT: int
    
    # 文件上传配置
    MAX_FILE_SIZE: int
    ALLOWED_FILE_TYPES: List[str]
    UPLOAD_DIR: str
    
    # 分页配置
    DEFAULT_PAGE_SIZE: int
    MAX_PAGE_SIZE: int
    
    # 邮件配置（可选）
    SMTP_HOST: Optional[str] = None
    SMTP_PORT: int
    SMTP_USER: Optional[str] = None
    SMTP_PASSWORD: Optional[str] = None
    SMTP_FROM_EMAIL: Optional[str] = None
    
    # 日志配置
    LOG_LEVEL: str
    LOG_FILE: str
    
    class Config:
        env_file = ".env"
        case_sensitive = True


# 创建全局配置实例
settings = Settings()


def get_database_url() -> str:
    """获取数据库连接URL"""
    # 如果URL中已经包含了认证信息，则直接使用
    if "@" in settings.MONGODB_URL:
        return f"{settings.MONGODB_URL}/{settings.MONGODB_DATABASE}"
    # 否则，使用单独的用户名和密码构建URL
    else:
        auth_part = f"{settings.MONGODB_USER}:{settings.MONGODB_PASSWORD}@" if settings.MONGODB_USER and settings.MONGODB_PASSWORD else ""
        base_url = settings.MONGODB_URL.replace("mongodb://", "")
        return f"mongodb://{auth_part}{base_url}/{settings.MONGODB_DATABASE}"


def get_redis_url() -> str:
    """获取Redis连接URL"""
    if settings.REDIS_PASSWORD:
        # 如果有密码，构建带密码的URL
        base_url = settings.REDIS_URL.replace("redis://", "")
        return f"redis://:{settings.REDIS_PASSWORD}@{base_url}"
    return settings.REDIS_URL


def is_development() -> bool:
    """判断是否为开发环境"""
    return settings.DEBUG


def is_production() -> bool:
    """判断是否为生产环境"""
    return not settings.DEBUG